import os
import shutil

def build():
    current_path = os.path.dirname(__file__)
    project_path = os.path.dirname(os.path.dirname(current_path))
    target_path = os.path.join(project_path, 'orgsync', 'src', 'main', 'resources', 'templates')
    ui_target_path = os.path.join(target_path, 'index')
    admin_target_path = os.path.join(target_path, 'admin')
    mobile_target_path = os.path.join(target_path, 'mobile')
    ui_build_path = os.path.join(project_path, 'orgsync-ui', 'build')
    copy_files(ui_build_path, ui_target_path, 'index')

def copy_files(build_path, target_path, template_path):
    if not os.path.exists(build_path):
        return
    os.makedirs(target_path, exist_ok=True)
    html_path = os.path.join(target_path, 'index.html')
    static_path = os.path.join(target_path, 'static')
    if os.path.exists(html_path):
        os.remove(html_path)
    if os.path.isdir(static_path):
        shutil.rmtree(static_path)
    shutil.copy2(os.path.join(build_path, 'index.html'), html_path)
    shutil.copytree(os.path.join(build_path, 'static'), static_path)
    content = ''
    with open(html_path, 'r') as file:
        content = file.read()
    content = content.replace('/static/', '/%s/static/' % template_path)
    with open(html_path, 'w') as file:
        file.write(content)

if __name__ == '__main__':
    build()
